﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MINERP.MODEL.AutoOrder_Fuji;
using MINERP.BLL.Common;
using System.IO;

namespace MINERP.BLL.AutoOrder
{
    /// <summary>
    /// 全程监控文件夹操作类
    /// </summary>
    public class RemoteMonitorFolderBLL_Fuji
    {
        private string _strRemoteFolderPath = string.Empty;

        /// <summary>
        /// 得到监控文件夹下的所有含有order.xml的文件夹
        /// </summary>
        /// <returns></returns>
        public List<AutoOrderFolder_Info> GetAllFolderList()
        {
            List<AutoOrderFolder_Info> result = new List<AutoOrderFolder_Info>();

            if (string.IsNullOrEmpty(_strRemoteFolderPath))
            {
                _strRemoteFolderPath = FileDirPathBLL.GetRemoteOrderFolder();
            }

            DirectoryInfo remoteFolder = new DirectoryInfo(_strRemoteFolderPath);//在监控文件下放的全是以odrder num命名的文件夹，这些文件下直接就放个照片以及XML文档
            foreach (var di in remoteFolder.GetDirectories())
            {
                AutoOrderFolder_Info newOne = null;

                newOne = GetOneFromSomeFolder(di);
                if (newOne != null)
                {
                    result.Add(newOne);
                }
            }

            return result.OrderBy(of => of.CreateTime).ToList();
        }

        /// <summary>
        /// 从某个目录得到该目录下的关于自动开单的实体
        /// </summary>
        /// <param name="folderPath"></param>
        /// <returns></returns>
        public AutoOrderFolder_Info GetOneFromSomeFolder(string folderPath)
        {
            AutoOrderFolder_Info result = null;
            if (!string.IsNullOrEmpty(folderPath))
            {
                DirectoryInfo di = new DirectoryInfo(folderPath);
                result = GetOneFromSomeFolder(di);
            }
            return result;
        }

        /// <summary>
        /// 从某个目录得到该目录下的关于自动开单的实体
        /// </summary>
        /// <param name="di"></param>
        /// <returns></returns>
        public AutoOrderFolder_Info GetOneFromSomeFolder(DirectoryInfo di)
        {
            AutoOrderFolder_Info result = null;

            foreach (var fi in di.GetFiles("order_v2.xml"))
            {
                
                string newXmlPath=string.Empty;
                if (!ModifyOriginalXml(fi.FullName, out newXmlPath))
                    continue;

                //如果有则找到了
                result = new AutoOrderFolder_Info();
                result.CreateTime = fi.CreationTime;
                result.FolderPath = di.FullName;
                result.FolderName = result.FolderPath.Substring(result.FolderPath.LastIndexOf("\\") + 1);
                //result.OrderXMLpath = fi.FullName;
                result.OrderXMLpath = newXmlPath;
                result.Status = AutoOrderStatus.WaitDownLoad;
                break;
            }
            return result;
        }

        /// <summary>
        /// 删除XML中的命名空间，然后别存为原文件名+_WH.xml
        /// </summary>
        /// <param name="xmlFileName"></param>
        private bool ModifyOriginalXml(string OrigianlXmlPath, out string newXmlPath)
        {
            newXmlPath = string.Empty;
            StreamReader sr = new StreamReader(OrigianlXmlPath, System.Text.Encoding.UTF8);//创建读取文件流
            StringBuilder sBuilder = new StringBuilder();
            string strContext = null;
            try
            {
                while ((strContext = sr.ReadLine()) != null)
                {
                    sBuilder.AppendLine(strContext);//将读取文件流写入缓存
                }
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                sr.Close();
            }
            ///替换出错部分
            sBuilder.Replace("xmlns=\"http://ips.poi.de/schemas/orderexport\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", "");
            sBuilder.Replace("xsi:schemaLocation=\"http://ips.poi.de/schemas/orderexport http://ips.poi.de/schemas/orderexport/schemaV2_0.xsd\"", "");
            ///将文件另存      
            FileInfo fileInfo = new FileInfo(OrigianlXmlPath);
            newXmlPath = fileInfo.DirectoryName + "\\" + fileInfo.Name.Substring(0, fileInfo.Name.LastIndexOf('.')) + "_WH.xml";
            if (File.Exists(newXmlPath))
            {
                File.Delete(newXmlPath);
            }
            StreamWriter sWriter = File.CreateText(newXmlPath);
            try
            {
                sWriter.Write(sBuilder);
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                sWriter.Close();
            }

            return true;
        }

        public void OpenRemoteMonitorFolder()
        {
            if (_strRemoteFolderPath != null)
            {
                FileBLL.OpenFoler(_strRemoteFolderPath);
            }

        }
    }
}
